package com.lw.leetcode.arr.a;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 1640. 能否连接形成数组
 *
 * @author liw
 * @version 1.0
 * @date 2022/9/22 9:08
 */
public class CanFormArray {

    public static void main(String[] args) {
        CanFormArray test = new CanFormArray();

        // true
        int[] arr = {15, 88};
        int[][] pieces = {{88}, {15}};

        // false
//        int[] arr = {49, 18, 16};
//        int[][] pieces = {{16, 18, 49}};

        // true
//        int[] arr = {91, 4, 64, 78};
//        int[][] pieces = {{78}, {4, 64}, {91}};

        boolean b = test.canFormArray(arr, pieces);
        System.out.println(b);
    }

    public boolean canFormArray(int[] arr, int[][] pieces) {
        Map<Integer, Integer> map = new HashMap<>();
        int m = pieces.length;
        for (int i = 0; i < m; i++) {
            map.put(pieces[i][0], i);
        }
        int length = arr.length;
        int[] values = null;
        int index = 0;
        for (int i = 0; i < length; i++) {
            if (values == null) {
                Integer t = map.get(arr[i]);
                if (t == null) {
                    return false;
                }
               values = pieces[t];
                index++;
            } else {
                if (arr[i] != values[index]) {
                    return false;
                }
                index++;
            }
            if (index == values.length) {
                values = null;
                index = 0;
            }
        }
        return true;
    }

}
